package com.xigege.nio.NIO案例多线程;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static com.xigege.nio.bufferAndChannel.util.ByteBufferUtil.debugAll;

/**
 * 多线程NIO服务器
 */
public class MultiThreadServer {
    public static void main(String[] args) throws IOException {
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(6666));
        // 1. 创建固定数量的worker
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("work-" + i);
        }

        // 不能在此执行worker的注册，否则直接在 selector.select() 阻塞住
        // 从而执行 sc.register(worker.selector, SelectionKey.OP_READ, null) 时就会阻塞
        // worker.register();
        AtomicInteger atomicInteger = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    System.out.println("connected...." + sc.getRemoteAddress());
                    // 2.关联selector
                    System.out.println("before register...." + sc.getRemoteAddress());
                    // 从workers中取一个来注册
                    workers[atomicInteger.getAndIncrement() % workers.length].register(sc);
                    System.out.println("after register...." + sc.getRemoteAddress());
                }
            }
        }
    }

    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private final String name;
        private volatile boolean start;
        private final ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        public void register(SocketChannel sc) throws IOException {
            if (!this.start) {
                this.thread = new Thread(this, name);
                this.selector = Selector.open();
                this.thread.start();
                this.start = true;
            }
            // 使用一个queue解耦，传递数据
            queue.add(() -> {
                try {
                    sc.register(selector, SelectionKey.OP_READ, null);
                } catch (ClosedChannelException e) {
                    e.printStackTrace();
                }
            });
            // 在这里唤醒worker的selector
            selector.wakeup();

            // 不使用队列的情况下，也可以使用以下的代码来保证注册时selector不会被阻塞
            // wakeup方法就像发一张票，无论wakeup方法在select方法之前或者之后执行，都可以保证selector被唤醒
            // 从而保证socketChannel注册时不会被阻塞
//            selector.wakeup();
//            sc.register(selector, SelectionKey.OP_READ, null);
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select();
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();
                    }
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        iterator.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            int read = channel.read(buffer);
                            if (read == -1) {
                                key.cancel();
                            } else {
                                buffer.flip();
                                System.out.println(this.name + "从" + channel.getRemoteAddress() +
                                        "接收到：" + Charset.defaultCharset().decode(buffer));
                                debugAll(buffer);
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}